import json

from django.shortcuts import redirect
from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin

from users.tools.auth import decode_token

AUTH_CHECK_WHITE_LIST = [
    '/users/'
]


class AuthMiddleWare(MiddlewareMixin):

    @staticmethod
    def process_request(request):
        # print(request.META.get("CONTENT_TYPE"))
        if request.method == 'POST':
            if "multipart/form-data;" in request.META.get("CONTENT_TYPE"):
                token = request.META.get("HTTP_TOKEN")
                status, de_token = decode_token(token)
                if status:
                    pass
                else:
                    return redirect(reverse("Users:token_expired"))
            else:
                # print(request.body)
                ask = json.loads(str(request.body, encoding='UTF-8'))
                request.ask = ask
                # print('ask--->', ask)
                if request.path in AUTH_CHECK_WHITE_LIST:
                    pass
                else:
                    if 'token' in ask:
                        token = ask['token']
                        status, de_token = decode_token(token)
                        if status:
                            pass
                        else:
                            return redirect(reverse("Users:token_expired"))
                    else:
                        print('not in ask')
                        return redirect(reverse("Users:token_expired"))
